package com.jl.smartcard.ui.views.cardlist;

import java.util.List;

import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.widgets.TreeColumn;

import com.jl.card.parse.IAPDUComponent;

public class TreeContentProvider implements ITreeContentProvider{

	private TreeModel input;
	
	private TreeViewer treeViewer;
	
	@Override
	public void dispose() {
		disposeColumns();
	}

	@Override
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		this.treeViewer = (TreeViewer) viewer;
		this.input = (TreeModel) newInput;
	}

	@Override
	public Object[] getElements(Object inputElement) {
		disposeColumns();
		List<IAPDUComponent> l =  input.getElements();
		return l.toArray(new IAPDUComponent[]{});
	}

	/**
	 * dispose all columns
	 */
	private void disposeColumns() {
		TreeColumn[] columns = treeViewer.getTree().getColumns();
		for(int i = 0 ;i < columns.length;i++){
			columns[i].dispose();
		}
	}

	@Override
	public Object[] getChildren(Object parentElement) {
		if(parentElement instanceof IAPDUComponent){
			return ((IAPDUComponent)parentElement).childrenToArray();
		}
		return null;
	}

	@Override
	public Object getParent(Object element) {
		if(element instanceof IAPDUComponent){
			return ((IAPDUComponent)element).getParent();
		}
		return null;
	}

	@Override
	public boolean hasChildren(Object element) {
		if(element instanceof IAPDUComponent){
			return ((IAPDUComponent)element).hasChildren();
		}
		return false;
	}

}
